package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CookieUtil;
import com.nowcoder.community.util.HostHolder;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @ClassName LoginTicketInterceptor
 * @Description
 * @Author hhwu
 * @Date 2022/5/20 12:55
 * Version 1.0
 **/
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * @Author hhwu
         * @Description //TODO 将cookie中的凭证对应的用户user信息存入hostHolder中,object是拦截的目标
         * @Date 20:44 2022/5/20
         * @Param [request, response, handler]
         * @return boolean
         **/
        // 从cookie中获取凭证
//        System.out.println("进入拦截器");
        String ticket = CookieUtil.getValue(request, "ticket");
//        System.out.println(ticket);
        if (ticket != null) {
            // 获取凭证完整记录
//            System.out.println("00000000000000000000000000000000000000000");
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            // 检查凭证是否有效
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {// 如果凭证有效
                // 根据凭证查询用户
                User user = userService.findUserById(loginTicket.getUserId());
                // 在本次请求中持有用户,将user保存到当前线程中
//                System.out.println("给hostHolder传入user对象");
                hostHolder.setUser(user);

                // 构建用户认证的结果，并存入SecurityContext，以便于Security进行授权。
                // 注意：如果我们在SecurityConfig中配置了认证方式（那个没有被重写的configure），则security会自动将认证结果添加到SecurityContext中。但我们想用自己之前定义过的认证方式
                // 所有，只能自己手动将认证结果写入SecurityContext中
                Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), userService.getAuthorities(user.getId()));
                SecurityContextHolder.setContext(new SecurityContextImpl(authentication));// 存入
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        /**
         * @Author hhwu
         * @Description //TODO 将hostHolder中的对象放入modelAndview中
         * @Date 20:44 2022/5/20
         * @Param [request, response, handler, modelAndView]
         * @return void
         **/
        User user = hostHolder.getUser();
        if (user != null && modelAndView != null) {
//            System.out.println("mav传入user");
            modelAndView.addObject("loginUser", user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        /**
         * @Author hhwu
         * @Description //TODO 清除hostHolder中的对象
         * @Date 20:43 2022/5/20
         * @Param [request, response, handler, ex]
         * @return void
         **/
        hostHolder.clear();
        SecurityContextHolder.clearContext();// 清除对象权限
    }
}
